import { PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React from 'react';

interface IProps {
	fileList: Array<any>;
	requestData: any;
	handleUpload: ( imageList ) => void;
	handleDelete: ( imageList ) => void;
}

const UploadComponent = ( props: IProps ) => {
	const { fileList, handleUpload, handleDelete, requestData } = props;
	const serverUrl = `${ window.location.origin.indexOf( 'localhost' ) > -1 ? 'http://localhost:3001' : window.location.origin }/bdhapi/uploadfile`;

	const handleChange = ( info ) => {
		console.log( info );
		if ( info.file.status === 'done' ) {

			const response = info.file.response;
			if ( response.status !== 1 ) return message.error( response.message || '上传失败，请重试' );

			const url = response.data[ 0 ].imageUrl;

			const imageList = [ {
				uid: info.file.uid,
				name: info.file.name,
				url: url
			} ];

			handleUpload( imageList );

		} else if ( info.file.status === 'error' ) {
			message.error( `${ info.file.name } file upload failed.` );
		} else if ( info.file.status === 'removed' ) {
			handleDelete( fileList );
		}
	};

	return (
		<Upload
			accept='image/*'
			name="image"
			listType="picture-card"
			fileList={ fileList }
			action={ serverUrl }
			onChange={ handleChange }
			withCredentials={ true }
			data={ requestData }
		>
			{ fileList.length === 0 ? <div><PlusOutlined/></div> : null }
		</Upload>
	);
};

export default React.memo( UploadComponent );

